import base64
import re

from langchain_community.llms.ollama import Ollama
from utils.searchApi import SearchApi
from utils.HtmlControl import HtmlControl

model = ['phi3', 'llava-phi3', 'dolphin-llama3']
ollama = Ollama(
    base_url='http://localhost:11434',
    model=model[2]
)

# Example usage:
query = "百度飞桨是什么"
results = SearchApi.bing_search(query)
stingT = ''
if results:
    for result in results:
        #解码base64获得跳转后的url
        url = result.get("href")
        start_index = url.find('u=a1') + 4
        encoded_url = url[start_index:]
        encoded_url = re.sub(r'&ntb=1$', '', encoded_url)
        # print(encoded_url)
        #当字符串长度不是4的倍数的时候要用=补上位数
        missing_padding = len(encoded_url) % 4
        while missing_padding:
            encoded_url += '='
            missing_padding = len(encoded_url) % 4
        try:
            decoded_bytes = base64.b64decode(encoded_url)
            url = decoded_bytes.decode('utf-8')
        except:
            url = result.get("href")

        # print(url)
        abstract = result.get("abstract")
        HtmlContent,title = HtmlControl.getHtmlContent(url)
        if abstract == '':
            abstract = title
        print(abstract)
        stingT = f"""{stingT}
        摘要:{abstract}
        """

        # print(result.get("title"))
        # print(result.get("abstract"))
# print(stingT)
print(f"""
用户的提问:{query}
下面是用户在网页上搜索到的内容，作为ai助理，你需要根据用户的提问用中文总结一下:
{stingT}
""")
for chuck in ollama.stream(f"""
用户的提问:{query}
下面是用户在网页上搜索到的内容，作为说中文的ai助理，你需要根据这些内容完成用户的提问:
{stingT}
"""):
    print(chuck, end='', flush=True)
